<template>
  <div>
    <h2>一对一聊天（房间: {{ roomId }}）</h2>
    <div class="chat-box">
      <div v-for="(msg, index) in messages" :key="index">
        <strong>{{ msg.sender }}:</strong> {{ msg.message }}
      </div>
    </div>
    <input v-model="inputMessage" placeholder="输入消息" />
    <button @click="sendMessage">发送</button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const roomId = 'user1_user2';  // 聊天室ID（通常由后端生成）
const messages = ref([]);
const inputMessage = ref('');
let socket = null;

onMounted(() => {
  // 连接 WebSocket
  socket = new WebSocket(`ws://localhost:8000/ws/chat/${roomId}/`);

  socket.onmessage = (e) => {
    const data = JSON.parse(e.data);
    messages.value.push({
      sender: data.sender,
      message: data.message
    });
  };

  socket.onerror = (e) => {
    console.error('WebSocket 错误:', e);
  };
});

const sendMessage = () => {
  if (inputMessage.value.trim() && socket) {
    socket.send(JSON.stringify({
      message: inputMessage.value,
      sender: '当前用户'
    }));
    inputMessage.value = '';
  }
};
</script>

<style scoped>
.chat-box {
  height: 300px;
  overflow-y: scroll;
  border: 1px solid #ccc;
  padding: 10px;
}
</style>